package com.gxuwz.zhangjiahui.controller;

import com.gxuwz.zhangjiahui.entity.*;
import com.gxuwz.zhangjiahui.service.*;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhangjiahui
 * @since 2021-06-20
 */
@Controller
public class LoginController {

    @Autowired
    private IUserService iUserService;
    @Autowired
    private IRoleService iRoleService;
    @Autowired
    private IStudentService iStudentService;
    @Autowired
    private ITeamService iTeamService;
    @Autowired
    private IInstructorService iInstructorService;
    @Autowired
    private IBudgetService iBudgetService;
    @Autowired
    private IFundsService iFundsService;


    /**
     * 默认登录界面显示
     * @return
     */
    @RequestMapping(value = "/")
    @RequestBody
    public String login() {
        return "forward:/login";
    }

    /**
     * 默认登录界面显示
     * @return
     */
    @RequestMapping(value = "/login")
    public String toLogin() {
        return "login";
    }


    /**
     * 登录判断
     * @param user
     * @param request
     * @param response
     * @return
     */
    @RequestBody
    @PostMapping(value = "/login.action")
    public ModelAndView login(ModelAndView modelAndView, User user,
                              HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if(user.getUserId() == null){
            request.getSession().setAttribute("resultLogin", "full1");
            request.getRequestDispatcher("/login.html").forward(request, response);
        }else if(user.getPassWord() == null | user.getPassWord() == "" ){
            request.getSession().setAttribute("resultLogin", "full2");
            request.getRequestDispatcher("/login.html").forward(request, response);
        }else {
            User user2 = iUserService.findUserById(user);
            if(user2 == null){
                request.getSession().setAttribute("resultLogin", "none1");
                request.getRequestDispatcher("/login.html").forward(request, response);
            }else {
                if (user2.getPassWord().equals(user.getPassWord())) {
                    // 存放 user 到session中，用于aop和拦截器的判断！！！
                    request.getSession().setAttribute("user", user2);
                    // 根据 RoleId 查询对应id的名称
                    Role role = new Role();
                    role.setRoleId(user2.getRoleId());
                    Role role2 = iRoleService.findRoleById(role);
                    request.getSession().setAttribute("role", role2);
                    // 存放角色名称，到前端输出
                    List<Role> roles = iRoleService.findRoleAll();
                    request.getSession().setAttribute("roles", roles);


                    // 判断进来的账号是否为学生，如果是则查询是否存在团队
                    Student student = new Student();
                    student.setStuNo(user2.getUserId());
                    // 判断该用户是否为学生
                    if(iStudentService.findStudentById(student) != null){
                        // 是学生，然后进行信息存放
                        student = iStudentService.findStudentById(student);
                        // 判断是否存在团队，且是否为团队队长
                        if(student.getTeamId() != null && !student.getTeamId().equals("")){
                            Team team = new Team();
                            team.setTeamId(student.getTeamId());
                            // 查找团队信息
                            if(iTeamService.findTeamById(team) != null){
                                team = iTeamService.findTeamById(team);
                                if(team.getStuNo() != null && !team.getStuNo().equals("")){
                                    if(team.getStuNo().equals(student.getStuNo())){
                                        // 该成员是学生，存在团队，且为队长
                                        request.getSession().setAttribute("teamStuNo", 1);
                                        request.getSession().setAttribute("teamNo", team.getTeamId());
                                    }else {
                                        //该成员是学生，存在团队，但是不为队长
                                        request.getSession().setAttribute("teamStuNo", 2);
                                        request.getSession().setAttribute("teamNo", team.getTeamId());
                                    }
                                }
                            }
                        }else {
                            // 该成员是学生，不存在团队
                            request.getSession().setAttribute("teamStuNo", 3);
                        }
                        // 存放学生Id
                        request.getSession().setAttribute("studentNo", student.getStuNo());
                    }


                    // 判断是否是指导老师，是就只能看到自己指导的学生项目
                    if(role.getRoleId().equals("1003")){
                        // 存放二级学院信息
                        String ID = user2.getUserId();
                        // 判断是指导老师还是学院部门，获取二级学院编号
                        Instructor instructor = new Instructor();
                        instructor.setInstructorId(ID);
                        instructor = iInstructorService.findInstructorById(instructor);
                        if(instructor != null){
                            request.getSession().setAttribute("instructorNow", instructor.getInstructorId());
                        }
                    }


                    // 查询对应userId的权限String集合，存放到session中，用于拦截器的判断！！！。
                    System.out.println("用户：" + user.getUserId());
                    System.out.println("拥有权限名称：=========================");
                    String[] limits = new String[1000];
                    if(role2.getRoleLimit() != null){
                        limits = role2.getRoleLimit().split(",");
                        for (int i = 0; i < limits.length; i++) {
                            System.out.print(limits[i] + ";");
                        }
                    }else {
                        System.out.println("权限为空！");
                    }
                    System.out.println("=====================================");
                    // 登录成功可以设置时间更长一些
                    //setMaxInactiveInterval(60) 60S内不做任何事情，Session就失效。比如，你刚登录了系统，接着跑去财务部收钱，                  
                    // 70S后回来，再继续操作系统，这时应该会提示重新登录。
                    request.getSession().setMaxInactiveInterval(60 * 2);
                    // 保存登录状态
                    Cookie ck = new Cookie("JSESSIONID", request.getSession().getId());
                    ck.setPath("/");
                    // session最长存在时间 (暂设1小时)
                    ck.setMaxAge(60 * 60);
                    response.addCookie(ck);
                    request.getSession().setAttribute("limits", limits);
                    modelAndView.setViewName("index");
                    return modelAndView;
                }else{
                    request.getSession().setAttribute("resultLogin", "none2");
                    request.getRequestDispatcher("/login.html").forward(request, response);
                }
            }
        }
        modelAndView.setViewName("error/404");

        // 清除session中的登录提示
        request.getSession().setAttribute("resultLogin", "");

        return modelAndView;
    }


    /**
     * 默认欢迎界面
     * @return
     */
    @RequestMapping(value = "/hello")
    public ModelAndView hello(ModelAndView modelAndView) {
        // 查询指导老师信息
        List<Instructor> instructorList = iInstructorService.findInstructorAll();
        modelAndView.addObject("instructorList", instructorList);

        // 查询团队信息
        List<Funds> fundsList = iFundsService.findFundsAll();
        modelAndView.addObject("fundsList", fundsList);

        // 根据年度查询预算方案
        Budget budget = new Budget();
        // 存放当前年份
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
        budget.setBudgetYear(formatter.format(new Date()));
        List<Budget> budgetList = iBudgetService.findBudgetByYear(budget);
        modelAndView.addObject("budgetList", budgetList);

        modelAndView.setViewName("/hello");

        return modelAndView;
    }

    /**
     * 默认欢迎界面
     * @return
     */
    @RequestMapping(value = "/errorNow")
    public ModelAndView errorNow(ModelAndView modelAndView) {
        modelAndView.setViewName("/error/400");
        return modelAndView;
    }


    /**
     * 退出登录
     * @return
     */
    @RequestMapping(value = "/loginEnd")
    public String loginEnd(HttpServletRequest request, HttpServletResponse response){
        request.getSession().invalidate();
        return "forward:/login";
    }

}
